//
//  FYTimer.m
//  GCD-TimerDeom
//
//  Created by FelixYin on 2020/4/11.
//  Copyright © 2020 FelixYin. All rights reserved.
//

#import "FYTimer.h"

@implementation FYTimer

static NSMutableDictionary *timers;

+ (void)initialize
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        timers = [[NSMutableDictionary alloc] init];
    });
}

+ (NSString *)schedule:(FYTimerBlock)block start:(NSTimeInterval)start interval:(NSTimeInterval)interval repeat:(BOOL)repeat async:(BOOL)async{
        static int i = 0;
        if (!block) {
            return nil;
        }
        NSString *timerID = [@"" stringByAppendingFormat:@"%d",i++];
        //定时器执行任务的队列，也可以使用其他队里执行定时器任务(同步时在祝队列中，异步时放在其他线程中)
        dispatch_queue_t queue = async ? dispatch_get_global_queue(0, 0) : dispatch_get_main_queue();
        
        //创建定时器
        dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        
        //设置定时器开始时间及执行任务的频率
//        uint64_t start = start; //两秒后执行
//        uint64_t interval = interval; //每1秒执行一次任务
        dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, start*NSEC_PER_SEC), interval*NSEC_PER_SEC, 0);
        
        //设置定时器任务
        dispatch_source_set_event_handler(timer, ^{
            block(@"");
            if (!repeat) {
                //如果不重复的话执行完任务 直接取消
                dispatch_source_cancel(timer);
            }
        });
//        dispatch_source_set_event_handler_f(timer, timerFire);
        //启动定时器
        dispatch_resume(timer);
        [timers setObject:timer forKey:timerID];
        return timerID;
}


+ (void)cancleSchedule:(NSString *)timerID{
    if(timers.allKeys.count < 1){
        return;
    }
    dispatch_source_t timer = timers[timerID];
    dispatch_source_cancel(timer);
    [timers removeObjectForKey:timerID];
}

@end
